package com.alinesno.cloud.gateway.admin.proxy;

import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alinesno.cloud.common.facade.enums.HasStatusEnums;
import com.alinesno.cloud.gateway.admin.entity.GateBusinessServerEntity;
import com.alinesno.cloud.gateway.admin.service.IGateBusinessServerService;
import com.alinesno.cloud.gateway.core.dispather.mina.bean.BusinessServerBean;
import com.alinesno.cloud.gateway.core.dispather.mina.server.MinaSocketServer;

/**
 * 配置服务
 * 
 * @author WeiXiaoJin
 * @since 2020年1月30日 下午19:45:08
 */
@Component
public class MinaSocketConfig implements InitializingBean {

	@Autowired
	private IGateBusinessServerService serverService;

	private static final Logger log = LoggerFactory.getLogger(MinaSocketConfig.class);

	/**
	 * 启动mina服务
	 * 
	 * @return
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
		log.debug("启动socket服务.");
		List<GateBusinessServerEntity> list = serverService.findAllByHasStatus(HasStatusEnums.LEGAL.value);

		if (list != null && list.size() > 0) {
			for (GateBusinessServerEntity e : list) {
				BusinessServerBean bean = new BusinessServerBean();

				// 配置属性
				// BeanUtils.copyProperties(e, bean);

				bean.setServerId(e.getId());
				bean.setServerPort(Integer.parseInt(e.getServerPort()));
				bean.setBusinessCode(e.getAuthType());
				bean.setBusinessDesc(e.getServerDesc());

				try {
					MinaSocketServer.startServerByPort(bean);
				} catch (IOException e1) {
					log.error("服务启动异常:", e1);
				}
			}
		}
	}

}
